package cn.libinal.scloud.base.oauth.security.token;

import cn.libinal.scloud.base.common.dto.PermissionDto;
import cn.libinal.scloud.base.common.dto.RoleDto;
import cn.libinal.scloud.base.common.dto.UserDto;
import com.google.common.collect.Sets;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Set;

/**
 * Description: 自定义用户凭证
 *
 * @author libinal
 * Created on 2019/3/15 11:14
 **/

public class CustomUserDetails implements UserDetails {

    private UserDto user;

    /**
     * 构造方法
     * @param user 用户信息
     */
    public CustomUserDetails(UserDto user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> grantedAuthorities = Sets.newHashSet();
        if (!user.getRoles().isEmpty()) {
            Set<RoleDto> roles = user.getRoles();
            roles.forEach(roleDto -> {
                // 角色必须是ROLE_开头，可以在数据库中设置
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(roleDto.getSn());
                grantedAuthorities.add(grantedAuthority);
                // 获取权限
                if (!roleDto.getPermissions().isEmpty()) {
                    Set<PermissionDto> permissionDtos = roleDto.getPermissions();
                    permissionDtos.forEach(permissionDto -> {
                        GrantedAuthority ga = new SimpleGrantedAuthority(permissionDto.getSn());
                        grantedAuthorities.add(ga);
                    });
                }
            });
        }
        return grantedAuthorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
